const ApiLog = require('../models/ApiLog');


const routeDescriptions = {
  'GET /api/datasources': '获取数据源列表',
  'POST /api/datasources': '新增数据源',
  'GET /api/datasources/:id': '获取数据源详情',
  'PUT /api/datasources/:id': '更新数据源',
  'DELETE /api/datasources/:id': '删除数据源',
  'GET /api/models': '获取模型列表',
  'POST /api/models': '新增模型',
  'GET /api/models/:id': '获取模型详情',
  'PUT /api/models/:id': '更新模型',
  'DELETE /api/models/:id': '删除模型',
  'GET /api/modeltasks': '获取模型任务列表',
  'POST /api/modeltasks': '新增模型任务',
  'GET /api/modeltasks/:id': '获取模型任务详情',
  'PUT /api/modeltasks/:id': '更新模型任务',
  'DELETE /api/model-tasks/:id': '删除模型任务',
  'GET /api/alarms': '获取告警列表',
  'POST /api/alarms': '新增告警',
  'GET /api/alarms/:id': '获取告警详情',
  'PUT /api/alarms/:id': '更新告警',
  'DELETE /api/alarms/:id': '删除告警',
  'GET /api/layers': '获取图层列表',
  'POST /api/layers': '新增图层',
  'GET /api/layers/:id': '获取图层详情',
  'PUT /api/layers/:id': '更新图层',
  'DELETE /api/layers/:id': '删除图层',
  'GET /api/plotting': '获取标绘列表',
  'POST /api/plotting': '新增标绘',
  'GET /api/plotting/:id': '获取标绘详情',
  'PUT /api/plotting/:id': '更新标绘',
  'DELETE /api/plotting/:id': '删除标绘',
  'POST /api/upload': '文件上传',
  'POST /api/select': '文件选择',
  'GET /api/foldselect': '获取文件路径列表',
};

function getDescription(method, path) {
  // First, try a direct match
  let key = `${method} ${path}`;
  if (routeDescriptions[key]) {
    return routeDescriptions[key];
  }

  // If not found, try to match parameterized routes (e.g., /api/models/123)
  const pathSegments = path.split('/');
  for (const route in routeDescriptions) {
    const routeSegments = route.split(' ');
    const routeMethod = routeSegments[0];
    const routePath = routeSegments[1];
    const routePathSegments = routePath.split('/');

    if (routeMethod === method && pathSegments.length === routePathSegments.length) {
      const isMatch = routePathSegments.every((segment, i) => {
        return segment.startsWith(':') || segment === pathSegments[i];
      });
      if (isMatch) {
        return routeDescriptions[route];
      }
    }
  }

  return '未知操作'; // Default description
}


module.exports = async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;

  try {
    // Don't log requests to the log viewing endpoint itself
    if (ctx.path === '/api/api-logs') {
      return;
    }

    const description = getDescription(ctx.method, ctx.path);

    await ApiLog.create({
      path: ctx.path,
      method: ctx.method,
      status: ctx.status,
      ip: ctx.request.ip,
      response_time: ms,
      description: description,
    });
  } catch (error) {
    // If logging fails, just print to console and don't crash the app
    console.error('Failed to log API access:', error);
  }
};